<?php

namespace App\Http\Controllers\Admin;

use App\Http\Model\Navs;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;
use phpDocumentor\Reflection\DocBlock\Tags\nav;

class NavsController extends CommonController
{
    public function index()
    {
        $data = Navs::orderBy('nav_order','asc')->get();
        return view('admin.navs.index',compact('data'));
    }

    public function changeOrder(Request $request)
    {
        $input = $request->input();
        $nav = Navs::find($input['nav_id']);
        $nav->nav_order = $input['nav_order'];
        $re = $nav->update();
        if($re){
            $data = [
                'status'=>0,
                'msg'=>'导航排序更新成功,请您刷新页面！'
            ];
        }else{
            $data = [
                'status'=>1,
                'msg'=>'导航排序更新失败，请稍后再试试！'
            ];
        }
        return $data;
    }

    //  admin/navs/create  添加导航
    public function create()
    {
        return view('admin/navs/add');
    }

    //admin/navs/store  添加导航提交方法
    public function store(Request $request)
    {
        $input = $request->except('_token');
        $rules = [
            'nav_name'=>'required',
            'nav_url'=>'required',
        ];
        $message = [
            'nav_name.required'=>'导航名称是必须要填写！',
            'nav_url.required'=>'导航URL是必须要填写！',
        ];
        $validator = Validator::make($input,$rules,$message);
        if($validator->passes()){
            $re = Navs::create($input);
            if($re){
                return redirect('admin/navs');
            }else{
                return back()->with('errors',"导航填写失败，请稍后再重试！");
            }
        }else{
            return back()->withErrors($validator);
        }
    }

    //  admin/navs/{nav_id}/edit 编辑导航
    public function edit($nav_id)
    {
        $field = Navs::find($nav_id);
        return view('admin.navs.edit',compact('field'));
    }

    //  admin/navs/{nav_id}   更新导航修改数据
    public function update(Request $request,$nav_id)
    {
        $input = $request->except('_token','_method');
        $re = Navs::where('nav_id',$nav_id)->update($input);
        if($re){
            return redirect('admin/navs');
        }else{
            return back()->with('errors',"数据更新失败，请稍后再重试！");
        }
    }

    // delete  admin/nav/{nav_id}  删除导航
    public function destroy($nav_id)
    {
        $re = Navs::where('nav_id',$nav_id)->delete();
        if($re){
            $data = [
                'status'=>0,
                'msg'=>'删除成功！'
            ];
        }else{
            $data = [
                'status'=>1,
                'msg'=>'删除失败，请稍后再试试！'
            ];
        }
        return $data;
    }

}
